package org.sensation.server.file.transfer.request;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;

public class FileChannelRequest {
	private static final int BUFFER_SIZE = 10;
	private DatagramChannel channel;
	private ByteBuffer buffer;
	private SocketAddress socketAddress;
	
	public FileChannelRequest(SelectionKey key) {
		super();
		setupDataGramChannel(key);
		setupByteBuffer();
	}

	public ByteBuffer receive() throws IOException{
		socketAddress = channel.receive(buffer);
		return buffer;
	}
	
	public void send(ByteBuffer sendBuffer) throws IOException{
		channel.send(sendBuffer, socketAddress);
	}
	
	public void close() throws IOException{
		if(channel != null){
			try {
				channel.close();
			} catch (Exception e) {
				channel.close();
			}
		}
	}
	
	private void setupDataGramChannel(SelectionKey key) {
		this.channel = (DatagramChannel) key.channel();
	}
	
	private void setupByteBuffer(){
		this.buffer = ByteBuffer.allocate(BUFFER_SIZE);
	}
	
	private InetSocketAddress getInetSocketAddress() {
		InetAddress inetAddress = channel.socket().getInetAddress();
		InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 5880);
		return inetSocketAddress;
	}
}
